package com.tencent.sr.iris.activity.service.activity;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.tencent.sr.iris.activity.common.enums.TaskEstimateStatusEnum;
import com.tencent.sr.iris.activity.common.enums.TaskRecordAwardIssueStatusEnum;
import com.tencent.sr.iris.activity.common.enums.UserTaskStatusEnum;
import com.tencent.sr.iris.activity.interfaces.enums.IsParticipatedEnum;
import com.tencent.sr.iris.activity.interfaces.request.acticity.BatchDataRequest;
import com.tencent.sr.iris.activity.interfaces.response.activity.BatchStatisticsResponse;
import com.tencent.sr.iris.activity.repository.mapper.example.TIrisUserTaskRecordExample;
import com.tencent.sr.iris.activity.repository.singlemapper.example.TIrisUserTaskBatchDataExample;
import com.tencent.sr.iris.activity.service.util.UserTaskBatchDataUtils;
import com.tencent.sr.rmall.material.interfaces.enums.EYesNo;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Map;

public abstract class AbstractNormalStatisticsHandler extends EsDataOperateService
        implements BatchDataStatisticsHandler {

    @Value("${env.es.batch.data.index.name:user-task-batch-data}")
    protected String indexName;

    @Resource
    protected IrisActivityTaskService irisActivityTaskService;

    @Resource
    protected ActivityCommonService activityCommonService;


    @Override
    protected String[] indices() {
        return new String[]{indexName};
    }

    /**
     * 统计
     *
     * @param special
     * @param request
     * @return
     */
    protected BatchStatisticsResponse statisticNormalOrSpecial(boolean special, BatchDataRequest request) {
        //参与团长数
        BoolQueryBuilder query = buildQuery(special);
        UserTaskBatchDataUtils.buildCondition(query, request);
        int participableUserCount = (int) esCountDistinct(query, TIrisUserTaskBatchDataExample.UID, "0");

        //上级团长数
        int upUserCount = (int) esCountDistinct(query, TIrisUserTaskBatchDataExample.PID, "0");

        //审核中下级数
        query = buildQuery(special);
        UserTaskBatchDataUtils.buildCondition(query, request);
        query.must(QueryBuilders.termQuery(StrUtil.toCamelCase(TIrisUserTaskBatchDataExample.USER_TASK_STATUS),
                        UserTaskStatusEnum.PROGRESS.getCode()))
                .must(QueryBuilders.termQuery(StrUtil.toCamelCase(TIrisUserTaskBatchDataExample.ESTIMATE_USER_TASK_STATUS),
                        TaskEstimateStatusEnum.FINISHED.getCode()));
        int auditingUserCount = (int) esCountDistinct(query, TIrisUserTaskBatchDataExample.UID, "0");

        //贡献下级数
        query = buildQuery(special).must(
                QueryBuilders.termQuery(StrUtil.toCamelCase(TIrisUserTaskBatchDataExample.IS_PARTICIPATED),
                        EYesNo.YES.name()));
        UserTaskBatchDataUtils.buildCondition(query, request);
        int isParticipatedUserCount = (int) esCountDistinct(query, TIrisUserTaskBatchDataExample.UID, "0");

        //可贡献
        query = buildQuery(special)
                .must(QueryBuilders.termsQuery(StrUtil.toCamelCase(TIrisUserTaskBatchDataExample.IS_PARTICIPATED),
                        Arrays.asList(IsParticipatedEnum.YES.name(), IsParticipatedEnum.NO.name())));
        UserTaskBatchDataUtils.buildCondition(query, request);
        int canContribute = (int) esCountDistinct(query, TIrisUserTaskBatchDataExample.UID, "0");

        //完成X阶下级数
        query = buildQuery(special);
        Integer finishTier = request.getFinishTier();
        if (finishTier != null) {
            query.must(QueryBuilders.termQuery(StrUtil.toCamelCase(TIrisUserTaskBatchDataExample.USER_TASK_STATUS),
                            UserTaskStatusEnum.FINISHED.getCode()))
                    .must(QueryBuilders.termQuery(TIrisUserTaskBatchDataExample.TIER, finishTier));
        }
        UserTaskBatchDataUtils.buildCondition(query, request);
        int finishTaskUserCount = (int) esCountDistinct(query, TIrisUserTaskBatchDataExample.UID, "0");

        //已发放奖励金,预估发放奖励金
        long commission = 0;
        long estimateCommission = 0;
        query = buildQuery(special)
                .must(QueryBuilders.termQuery(StrUtil.toCamelCase(TIrisUserTaskBatchDataExample.USER_TASK_STATUS),
                        UserTaskStatusEnum.FINISHED.getCode()))
                .must(QueryBuilders.termQuery(StrUtil.toCamelCase(TIrisUserTaskBatchDataExample.AWARD_ISSUE_STATUS),
                        TaskRecordAwardIssueStatusEnum.ISSUE_SUCCEED.getCode()))
                .mustNot(QueryBuilders.termQuery(StrUtil.toCamelCase(TIrisUserTaskBatchDataExample.IS_PARTICIPATED),
                        IsParticipatedEnum.LIMITED.name()));
        UserTaskBatchDataUtils.buildCondition(query, request);
        Map<String, Long> commissionMap = sumGroupBy("0", query,
                StrUtil.toCamelCase(TIrisUserTaskBatchDataExample.TASK_ID),
                StrUtil.toCamelCase(TIrisUserTaskRecordExample.SEND_AWARD));

        query = buildQuery(special).must(QueryBuilders
                        .termQuery(StrUtil.toCamelCase(TIrisUserTaskBatchDataExample.ESTIMATE_USER_TASK_STATUS),
                                TaskEstimateStatusEnum.FINISHED.getCode()))
                .mustNot(QueryBuilders.termQuery(StrUtil.toCamelCase(TIrisUserTaskBatchDataExample.IS_PARTICIPATED),
                        IsParticipatedEnum.LIMITED.name()));
        UserTaskBatchDataUtils.buildCondition(query, request);
        Map<String, Long> estimateCommissionMap = sumGroupBy("0", query,
                StrUtil.toCamelCase(TIrisUserTaskBatchDataExample.TASK_ID),
                StrUtil.toCamelCase(TIrisUserTaskRecordExample.SEND_AWARD));

        if (CollectionUtil.isNotEmpty(commissionMap) || CollectionUtil.isNotEmpty(estimateCommissionMap)) {
            commission = UserTaskBatchDataUtils.getCommission(commissionMap);
            estimateCommission = UserTaskBatchDataUtils.getCommission(estimateCommissionMap);
        }

        return new BatchStatisticsResponse()
                .setParticipableUserCount(participableUserCount)
                .setIsParticipatedUserCount(isParticipatedUserCount)
                .setFinishTaskUserCount(finishTaskUserCount)
                .setCommission(Math.toIntExact(commission))
                .setEstimateCommission(Math.toIntExact(estimateCommission))
                .setCanContribute(canContribute)
                .setAuditingUserCount(auditingUserCount)
                .setUpUserCount(upUserCount);
    }

    private BoolQueryBuilder buildQuery(boolean special) {
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        if (special) {
            query.must(QueryBuilders.termQuery(StrUtil.toCamelCase(TIrisUserTaskBatchDataExample.UID_SPECIAL_INVITE),
                    EYesNo.YES.getValue()));
        }
        return query;
    }
}
